using LF.Shared.Dtos.Input;
using LF.Shared.Dtos.Out;
using LF.Domain.Services;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.ObjectMapping;
using LF.Domain.Entities;
using LF.Application.Helpers;
using Microsoft.AspNetCore.Http;
using LF.Application.Extend;
using Microsoft.AspNetCore.Mvc;
using LF.Common;

namespace LF.Application.Services.Iml
{
    [Authorize]
    [ApiExplorerSettings(GroupName = SwaggerGroup.Ai)]
    public class KnowledgeBaseService : BaseService, IKnowledgeBaseService
    {
        private readonly IKnowledgeBaseManagerService _knowledgeBaseManager;
        private readonly IHttpContextAccessor _httpContext;

        public KnowledgeBaseService(
            IObjectMapper<LFModule> mapper,
            IKnowledgeBaseManagerService knowledgeBaseManager,
            IHttpContextAccessor httpContext,
            IGlobalManagerService globalManager) : base(mapper, globalManager)
        {
            _knowledgeBaseManager = knowledgeBaseManager;
            _httpContext = httpContext;
        }

        #region 知识库管理
        /// <summary>
        /// 获取知识库列表
        /// </summary>
        [LFAuthorize("获取知识库列表", "knowledge:base:list")]
        public Result<KnowledgeBaseSearchOut> List(KnowledgeBaseSearch search)
        {
            var result = _knowledgeBaseManager.GetKnowledgeBaseList(search.Index, search.PageSize, search.Name, search.Active);
            var list = _mapper.Map<List<KnowledgeBase>, List<KnowledgeBaseOut>>(result);
            var count = _knowledgeBaseManager.CountKnowledgeBase(search.Name, search.Active);
            return Ok(new KnowledgeBaseSearchOut { Items = list, TotalCount = count });
        }

        /// <summary>
        /// 获取知识库详情
        /// </summary>
        [LFAuthorize("查看知识库", "knowledge:base:read")]
        public Result<KnowledgeBaseOut> Detail(Guid id)
        {
            var knowledgeBase = _knowledgeBaseManager.GetKnowledgeBase(id);
            var result = _mapper.Map<KnowledgeBase, KnowledgeBaseOut>(knowledgeBase);
            return Ok(result);
        }

        /// <summary>
        /// 创建知识库
        /// </summary>
        [LFAuthorize("创建知识库", "knowledge:base:create")]
        public Result Create(KnowledgeBaseOut knowledgeBase)
        {
            var model = _mapper.Map<KnowledgeBaseOut, KnowledgeBase>(knowledgeBase);
            
            // 检查知识库名称是否已存在
            var existKnowledgeBases = _knowledgeBaseManager.GetKnowledgeBaseList(1, 10, model.Name, null);
            var existKnowledgeBase = existKnowledgeBases.FirstOrDefault(d => d.Name == model.Name);
            if (existKnowledgeBase != null && existKnowledgeBase.Name == model.Name)
            {
                return Error("知识库名称已存在!");
            }

            model.Id = Guid.NewGuid();
            model.Creator = _httpContext.HttpContext!.User.GetUserId().Value;
            
            if (_knowledgeBaseManager.InsertKnowledgeBase(model))
                return Ok();
            else
                return Error("创建失败!");
        }

        /// <summary>
        /// 编辑知识库
        /// </summary>
        [LFAuthorize("编辑知识库", "knowledge:base:update")]
        public Result Update(KnowledgeBaseOut knowledgeBase)
        {
            if (knowledgeBase.Id == Guid.Empty)
                return Error("知识库ID不能为空!");
                
            var model = _mapper.Map<KnowledgeBaseOut, KnowledgeBase>(knowledgeBase);

            // 检查知识库名称是否已存在
            var existKnowledgeBases = _knowledgeBaseManager.GetKnowledgeBaseList(1, 10, model.Name, null);
            var existKnowledgeBase = existKnowledgeBases.FirstOrDefault(d => d.Name == model.Name);
            if (existKnowledgeBase != null && existKnowledgeBase.Name == model.Name && existKnowledgeBase.Id != knowledgeBase.Id)
            {
                return Error("知识库名称已存在!");
            }
            if (_knowledgeBaseManager.UpdateKnowledgeBase(model))
                return Ok();
            else
                return Error("更新失败!");
        }

        /// <summary>
        /// 删除知识库
        /// </summary>
        [LFAuthorize("删除知识库", "knowledge:base:delete")]
        public Result Delete(Guid id)
        {
            if (_knowledgeBaseManager.DeleteKnowledgeBase(id))
                return Ok();
            else
                return Error("删除失败!");
        }

        /// <summary>
        /// 获取所有知识库
        /// </summary>
        [LFAuthorize("获取知识库", "knowledge:base:list")]
        public Result<List<KnowledgeBaseOut>> GetAll()
        {
            var result = _knowledgeBaseManager.GetAllKnowledgeBase();
            var list = _mapper.Map<List<KnowledgeBase>, List<KnowledgeBaseOut>>(result);
            return Ok(list);
        }
        #endregion

        #region 知识库文件管理
        /// <summary>
        /// 获取知识库文件列表
        /// </summary>
        //[LFAuthorize("获取知识库文件列表", "knowledge:file:list")]
        public Result<KnowledgeFileSearchOut> FileList(KnowledgeFileSearch search)
        {
            var result = _knowledgeBaseManager.GetKnowledgeFileList(search.Index, search.PageSize, search.KnowledgeBaseId, search.FileName, search.Suffix);
            var list = _mapper.Map<List<KnowledgeFile>, List<KnowledgeFileOut>>(result);
            var count = _knowledgeBaseManager.CountKnowledgeFile(search.KnowledgeBaseId, search.FileName, search.Suffix);
            return Ok(new KnowledgeFileSearchOut { Items = list, TotalCount = count });
        }

        /// <summary>
        /// 获取知识库文件详情
        /// </summary>
        //[LFAuthorize("查看知识库文件", "knowledge:file:read")]
        public Result<KnowledgeFileOut> FileDetail(Guid id)
        {
            var knowledgeFile = _knowledgeBaseManager.GetKnowledgeFile(id);
            var result = _mapper.Map<KnowledgeFile, KnowledgeFileOut>(knowledgeFile);
            return Ok(result);
        }

        /// <summary>
        /// 创建知识库文件
        /// </summary>
        //[LFAuthorize("创建知识库文件", "knowledge:file:create")]
        public Result FileCreate(KnowledgeFileOut knowledgeFile)
        {
            var model = _mapper.Map<KnowledgeFileOut, KnowledgeFile>(knowledgeFile);

            // 检查同一知识库下文件名是否重复
            var existKnowledgeFiles = _knowledgeBaseManager.GetKnowledgeFileList(1, 10, model.KnowledgeBaseId, model.FileName, null);
            var existKnowledgeFile = existKnowledgeFiles.FirstOrDefault(d => d.FileName == model.FileName);
            if (existKnowledgeFile != null && existKnowledgeFile.FileName == model.FileName)
            {
                return Error("同一知识库下文件名已存在!");
            }

            model.Id = Guid.NewGuid();
            
            if (_knowledgeBaseManager.InsertKnowledgeFile(model))
                return Ok();
            else
                return Error("创建失败!");
        }

        /// <summary>
        /// 编辑知识库文件
        /// </summary>
        //[LFAuthorize("编辑知识库文件", "knowledge:file:edit")]
        public Result FileEdit(KnowledgeFileOut knowledgeFile)
        {
            if (knowledgeFile.Id == Guid.Empty)
                return Error("文件ID不能为空!");

            var model = _mapper.Map<KnowledgeFileOut, KnowledgeFile>(knowledgeFile);

            // 检查同一知识库下文件名是否重复
            var existKnowledgeFiles = _knowledgeBaseManager.GetKnowledgeFileList(1, 10, model.KnowledgeBaseId, model.FileName, null);
            var existKnowledgeFile = existKnowledgeFiles.FirstOrDefault(d => d.FileName == model.FileName);
            if (existKnowledgeFile != null && existKnowledgeFile.FileName == model.FileName && existKnowledgeFile.Id != knowledgeFile.Id)
            {
                return Error("同一知识库下文件名已存在!");
            }
            
            if (_knowledgeBaseManager.UpdateKnowledgeFile(model))
                return Ok();
            else
                return Error("更新失败!");
        }

        /// <summary>
        /// 删除知识库文件
        /// </summary>
        //[LFAuthorize("删除知识库文件", "knowledge:file:delete")]
        public Result FileDelete(Guid id)
        {
            if (_knowledgeBaseManager.DeleteKnowledgeFile(id))
                return Ok();
            else
                return Error("删除失败!");
        }
        #endregion
    }
} 